package com.linqi.freebie.utils

import androidx.compose.ui.graphics.Color
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.compose.runtime.mutableStateListOf
import java.text.SimpleDateFormat
import java.util.*

object CommandLineOutput {
    private val _lines = mutableStateListOf<LogEntry>()
    // 时间格式化器
    private val timeFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())

    val lines: List<LogEntry> get() = _lines

    // 日志级别定义
    enum class LogLevel(
        val emoji: String,
        val color: Color
    ) {
        INFO("ℹ️", Color(0xFF2196F3)),    // 蓝色
        DEBUG("🐛", Color(0xFF9C27B0)),   // 紫色
        WARN("⚠️", Color(0xFFFF9800)),    // 橙色
        ERROR("❌", Color(0xFFF44336)),   // 红色
        SUCCESS("✅", Color(0xFF4CAF50)) // 绿色
    }

    data class LogEntry(
        val timestamp: String,
        val level: CommandLineOutput.LogLevel,
        val message: String
    ) {
        override fun toString(): String {
            return "[$timestamp] ${level.emoji} $message"
        }
    }

    private suspend fun addEntry(text: String, level: LogLevel) {
        withContext(Dispatchers.Main) {
            val timestamp = timeFormatter.format(Date())
            _lines.add(LogEntry(timestamp, level, text))
        }
    }

    suspend fun appendLine(text: String, level: LogLevel = LogLevel.INFO) {
        addEntry(text, level)
    }

    suspend fun appendLines(texts: List<String>, level: LogLevel = LogLevel.INFO) {
        withContext(Dispatchers.Main) {
            texts.forEach { addEntry(it, level) }
        }
    }

    suspend fun clear() {
        withContext(Dispatchers.Main) {
            _lines.clear()
        }
    }

    fun size(): Int = _lines.size

    suspend fun info(text: String) = appendLine(text, LogLevel.INFO)
    suspend fun debug(text: String) = appendLine(text, LogLevel.DEBUG)
    suspend fun warn(text: String) = appendLine(text, LogLevel.WARN)
    suspend fun error(text: String) = appendLine(text, LogLevel.ERROR)
    suspend fun success(text: String) = appendLine(text, LogLevel.SUCCESS)
}
